//处理博客相关的路由
const {SuccessModel, ErrorModel} = require("../model/responseModel");
const {getList, getDetail, createNewBlog, updataedBlog, deleteBlogData} = require("../controllers/blog");
const {execSQL} = require("../db/mysql");
const handlerBlogRoute = (req, res) => {
    //定义处理路由的逻辑
    const method = req.method;
    const id = req.query.id;
    const postData = req.body;

    console.log(method, req.path);
    //接口们
    if (method === 'GET' && req.path === '/api/blog/List') {
        const sql = 'select * from blogs';
        // execSQL(sql,(err,result)=>{
        //     if(err){
        //         console.error('error',err);
        //         return ;
        //     }
        //     console.log('result',result);
        // })
        //转化成promis,防止要用查询结果rusult的时候嵌套很深
        //从回调到promise


        // execSQL(sql).then(result=>{
        //     console.log(result);
        // });

        const author = req.query.author || '';
        const keyword = req.query.keyword || '';
        //创建对应方法来拿对应作者和kw的数据
        const listDataPromise = getList(author, keyword);
        return listDataPromise.then((listData) => {
            return new SuccessModel(listData);
        });
        // return new SuccessModel(listData);
    }
    if (method === 'GET' && req.path === '/api/blog/detail') {

        const detailDataPromise = getDetail(id);
        return detailDataPromise.then((detailData) => {
            return new SuccessModel(detailData);
        });

    }
    if (method === 'POST' && req.path === '/api/blog/update') {
        //异步代码通常表示，开发语言有一种方式用来通知计算机 (应用)在代码的某个地方，必须等待某些事件在其他地方完成。
        const updataedBlogDataPromise = updataedBlog(id, postData);
        return updataedBlogDataPromise.then(updataedBlogData => {
            if (updataedBlogData) {
                return new SuccessModel('更新博客成功');
            } else return new ErrorModel('更新博客失败...');
        })

    }
    if (method === 'POST' && req.path === '/api/blog/new') {
        //作者尚未登录，还不知道，先用假数据
        const author = 'zhangsan';
        req.body.author = author;
        const newBlogDataPromise = createNewBlog(postData);
        return newBlogDataPromise.then(newBlogData => {
            return new SuccessModel(newBlogData);
        })
        //return new SuccessModel(newBlogData);
    }
    if (method === 'POST' && req.path === '/api/blog/delete') {
        const author = 'zhangsan';
        const deletedBlogDataPromise = deleteBlogData(id);
        //console.log(deletedBlogData);
        return deletedBlogDataPromise.then(deletedBlogData => {
            if (deletedBlogData) {
                return new SuccessModel('删除成功');
            } else return new ErrorModel('删除失败...');
        })

    }
}
//将接口导出
module.exports = handlerBlogRoute;